package com.example.examy.service;

import com.example.examy.entity.Product;

import java.math.BigDecimal;
import java.util.List;


public class OrderService {
    public BigDecimal buy(List<Product> plist,DiscountRule discountRule){
        if(plist==null || plist.size()==0){
            throw new RuntimeException("输出的商品为空");
        }
        BigDecimal result = BigDecimal.ZERO;

        for (Product product :plist) {
            //验证输入的参数
            if(product.getNums()<=0){
                throw new RuntimeException("商品的数量不能为0或者复数");
            }
            if(product.getNums()>1000){
                throw new RuntimeException("商品的数量不能超过1000");
            }
            //计算出当前商品的价格
            BigDecimal temp = product.getPrice().multiply(new BigDecimal(product.getPercentage())
            ).multiply( new BigDecimal(product.getNums()));

            result = result.add(temp);
        }
        //判断释放存储其他优惠
        if(discountRule!=null){
            result = discountRule.discount(result);
        }
        //设置保留两位小数,四舍五入
        result = result.setScale(2,BigDecimal.ROUND_HALF_UP);
        return  result;
    }
}
